package br.com.ravi.deposito.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

@WebServlet(urlPatterns = "/CarregaXML/*")
public class CarregaXML extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static List<String> attrList = new ArrayList<String>();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		File f = new File("c:/menu_update.xml");

		// Criamos uma classe SAXBuilder que vai processar o XML4
		SAXBuilder sb = new SAXBuilder();

		// Este documento agora possui toda a estrutura do arquivo.
		Document d;
		try {
			d = sb.build(f);

			// Recuperamos o elemento root
			Element datapacket = d.getRootElement();

			// Recuperamos os elementos filhos (children)
			List<Element> elements = datapacket.getChildren();
			Iterator<Element> i = elements.iterator();

			// Iteramos com os elementos filhos, e filhos do dos filhos
			while (i.hasNext()) {
				Element element = (Element) i.next();
				List<Element> children = element.getChildren();
				
				if (children != null) {
					Iterator<Element> fields = children.iterator();
					while(fields.hasNext()) {
						Element grandson = fields.next();
						String name = grandson.getName();
						if (!name.equals("ROW")) {
							List<Element> field = grandson.getChildren();
							Iterator<Element> iterator = field.iterator();
							
							while(iterator.hasNext()) {
								//aqui retorna fields
								Element next = iterator.next();
								Attribute attrname = next.getAttribute("attrname");
								attrList.add(attrname.getValue());
							}
						}
						else {
							for (String attr : attrList) {
								System.out.println("Field " + attr + " valor: " + grandson.getAttributeValue(attr));
							}
						}
					}
				}
			}
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
